import ArticleItem from '@/components/ArticleItem'
import { RootState } from '@/store'
import { getArticles } from '@/store/action/article'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

type Props = {
  channel_id: number
}

export default function ArticleList({ channel_id }: Props) {
  const { activeId } = useSelector((state: RootState) => state.channel)

  const { articles } = useSelector((state: RootState) => state.article)

  const dispatch = useDispatch()

  const list = articles[activeId]?.list

  const handleRefresh = async () => {
    await dispatch(getArticles({ channel_id, isRefresh: true }))
  }

  const [hasMore, setHasMore] = useState(true)

  const loading = useRef(false)

  const handleLoadMore = async () => {
    if (loading.current) return

    loading.current = true
    try {
      await dispatch(
        getArticles({ channel_id, timestamp: articles[channel_id].timestamp })
      )
    } catch (error) {
      setHasMore(false)
    }
    loading.current = false
  }

  useEffect(() => {
    if (list) return
    if (channel_id === activeId) {
      dispatch(getArticles({ channel_id }))
    }
  }, [activeId, channel_id, dispatch, list])

  if (!list) return null

  return (
    <div>
      <PullToRefresh onRefresh={handleRefresh}>
        {list.map((item) => (
          <ArticleItem
            key={item.art_id}
            article={item}
            style={{ padding: 10 }}
          />
        ))}
      </PullToRefresh>
      <InfiniteScroll loadMore={handleLoadMore} hasMore={hasMore} />
    </div>
  )
}
